import { connectWebsocket } from "@/utils/utils";
import { baseURL } from "./base";
import { decode } from "cbor-x";
import type { CargoStatus } from "./devices/cargo";
import { reactive, ref } from "vue";
import type { DropStatus } from "./devices/drop";
import type { HeatStatus } from "./devices/heat";

const url = `${baseURL}/ws/status`;

let otaProgCallback = (msg: string) => {

}

export function setOtaCb(cb: (m: string) => void) {
    otaProgCallback = cb;
}

export async function infoConnect() {
    await connectWebsocket(url, (data) => {
        onInfoData(data);
    })
    console.log('info ws connected');
}

const TY_INFO = 1;

const TY_ROBOT_STATUS = 2;
const TY_CARGO1_STATUS = 3;
const TY_CARGO2_STATUS = 4;
const TY_DROP_STATUS = 5;
const TY_DOOR_STATUS = 6;
const TY_HEAT_STATUS = 7;
const TY_WEIGHT_STATUS = 8;

const TY_OTA_STATUS = 9;
const TY_LOG = 10;

function onInfoData(data: Uint8Array) {
    const ty = data[0];
    const body = data.slice(1);

    switch (ty) {
        case TY_CARGO1_STATUS: {
            let status = decode(body) as CargoStatus;
            globalStatus.cargo1 = status;
        }; break;

        case TY_CARGO2_STATUS: {
            let status = decode(body) as CargoStatus;
            globalStatus.cargo2 = status;
        }; break;

        case TY_DROP_STATUS: {
            let status = decode(body) as DropStatus;
            globalStatus.drop = status;
           // console.log('drop', status);
        }; break;

        case TY_HEAT_STATUS: {
            let status = decode(body) as HeatStatus;
            globalStatus.heat = status;
        }; break;

        case TY_OTA_STATUS: onOtaInfo(data); break;
        case TY_LOG: onLog(data); break;

        default: console.log('unknown ty info data', ty);
    }
}

function onOtaInfo(data: Uint8Array) {
    const body = data.slice(1, data.length);
    const msg = decode(body) as string;
    otaProgCallback(msg);
}

function onLog(data: Uint8Array) {
    const body = data.slice(1, data.length);
    const msg = decode(body) as string;

    if (logInfos.value.length > 100) {
        logInfos.value = [];
    }
    logInfos.value.push(msg);
}

export const logInfos = ref<string[]>([]);

export interface GlobalStatus {
    cargo1: CargoStatus | null,
    cargo2: CargoStatus | null,
    drop: DropStatus | null,
    heat: HeatStatus | null,
}

export const globalStatus = reactive<GlobalStatus>({
    cargo1: null,
    cargo2: null,
    drop: null,
    heat: null,
});

